<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card class="box-card">
      <!-- 警告提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        :closable="false"
        type="warning"
        show-icon>
      </el-alert>
      <!-- 选择三级分类 -->
      <div style="margin: 15px 0;">
        选择商品分类：
        <el-cascader
          v-model="cascaderValue"
          :options="cates"
          :props="cascaderProps"
          @change="cascaderChange">
        </el-cascader>
      </div>

      <!-- tabs标签页 -->
      <el-tabs @tab-click="tabsClick" v-model="activeName">
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="addParamsDialogVisible = true" :disabled="buttonIsDisabled" size="mini" type="primary">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table border :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="removeTag(scope.row, index)">{{item}}</el-tag>
                <el-input
                  style="width:120px"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditParamsDialog(scope.row)" icon="el-icon-edit">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button  @click="addParamsDialogVisible = true" :disabled="buttonIsDisabled" size="mini" type="primary">添加属性</el-button>
          <!-- 动态参数表格 -->
          <el-table border :data="onlyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="removeTag(scope.row, index)">{{item}}</el-tag>
                <el-input
                  style="width:120px"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditParamsDialog(scope.row)" icon="el-icon-edit">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数 / 添加静态属性 -->
    <el-dialog
      :title="'添加' + (activeName === 'many' ? '动态参数' : '静态属性')"
      :visible.sync="addParamsDialogVisible"
      width="50%">
      <el-form :rules="addParamsFormRules" ref="addParamsFormRef" :model="addParamsForm" label-width="80px">
        <el-form-item prop="attr_name" label="参数名称">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑动态参数 / 编辑静态属性 -->
    <el-dialog
      :title="'编辑' + (activeName === 'many' ? '动态参数' : '静态属性')"
      :visible.sync="editParamsDialogVisible"
      width="50%">
      <el-form :rules="addParamsFormRules" ref="editParamsFormRef" :model="editParamsForm" label-width="80px">
        <el-form-item prop="attr_name" label="参数名称">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eaitParamsSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cates: [],
      cascaderValue: '',
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      activeName: 'only',
      manyTableData: [],
      onlyTableData: [],
      // 控制添加参数/属性 显示隐藏
      addParamsDialogVisible: false,
      // 表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单校验规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制编辑对话框
      editParamsDialogVisible: false,
      editParamsFormRef: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editParamsForm: {
        attr_name: ''
      },
      inputVisible: false,
      inputValue: ''
    }
  },

  computed: {
    // 添加参数/添加属性 按钮 是否禁用
    buttonIsDisabled () {
      return this.cascaderValue.length !== 3
    },
    // 获取三级分类id
    cateId () {
      if (this.cascaderValue.length === 3) {
        return this.cascaderValue[2]
      }
      return null
    }
  },

  created () {
    this.getGoodsCate()
  },

  methods: {
    // 获取商品分类
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')

      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.cates = res.data
    },
    // 获取动态参数/静态属性
    async getParams () {
      // 发送请求
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })

      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      // res.data： 可能是静态属性 可能是动态参数
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },
    // 级联选择期发生变化
    cascaderChange () {
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.onlyTableData = []
        this.manyTableData = []
      } else {
        this.getParams()
      }
    },
    // 点击tabs标签页
    tabsClick () {
      if (this.cateId) {
        this.getParams()
      }
    },
    // 点击确定添加参数&属性
    addParamsSubmit () {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addParamsDialogVisible = false
        this.getParams()
      })
    },
    showEditParamsDialog (row) {
      const { attr_name: attrName, attr_id: attrId } = row
      this.editParamsForm.attr_name = attrName
      this.editParamsForm.attrId = attrId
      this.editParamsDialogVisible = true
    },
    eaitParamsSubmit () {
      this.$refs.editParamsFormRef.validate(async flag => {
        if (!flag) return
        const attrId = this.editParamsForm.attrId
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${attrId}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editParamsDialogVisible = false
        this.getParams()
      })
    },
    removeParams (attrId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${attrId}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message({
          type: 'success',
          message: '删除成功!'
        },
        this.getParams()
        )
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        },
        this.getParams()
        )
      })
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''
        return true
      }
      console.log('实现添加功能')
      row.attr_vals.push(row.inputValue)
      this.updateAttrVals(row)
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async updateAttrVals (row) {
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) this.$message.error('更新失败')
      row.inputVisible = false
      row.inputValue = ''
      this.$message.success('更新成功')
    },
    removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      this.updateAttrVals(row)
    }
  }
}
</script>

<style scoped lang='less'>
  .el-tag {
    margin: 7px;
  }
</style>
